package val.to.server;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import val.to.ErrorHelper;


public class JsonUtils {
	
	private static SimpleDateFormat formatterUtc ;
	private static SimpleDateFormat formatter ;
	
	static {
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		formatterUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		formatterUtc.setTimeZone(TimeZone.getTimeZone("UTC"));  
	}
	
	public static String jsonDateFormatToUtc(Date date){
		//Expected format: '%Y-%m-%dT%H:%M:%S'
		//The date should be in UTC
		return formatterUtc.format(date).replace(' ', 'T');
	}
	
	public static String jsonDateFormat(Date date){
		//Expected format: '%Y-%m-%dT%H:%M:%S'
		return formatter.format(date).replace(' ', 'T');
	}
	
	public static String jsonDateFormatUtc(Date date){
		//Expected format: '%Y-%m-%dT%H:%M:%S'
		return formatterUtc.format(date).replace(' ', 'T');
	}
	
	public static Date dateFromJson(String json){
		
		//"2012-05-10T14:25:51.646040"
		//or:
		//"2012-05-10T14:25:51
		
		Date d = null;
		try {
			String date = json.substring(1, json.length() - 1).replace('T', ' ');
			d = formatterUtc.parse(date);
		} 
		catch (ParseException e) {
			ErrorHelper.handleError(e);
		}
		      
		return d;
	}
}
